package net.xdclass.mq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.model.CouponRecordMessage;
import net.xdclass.model.ProductMessage;
import net.xdclass.service.ProductService;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.locks.Lock;

/**
 * @Author NJUPT wly
 * @Date 2021/9/25 10:39 上午
 * @Version 1.0
 */
@Slf4j
@Component
@RabbitListener(queues = "${mqconfig.stock_release_queue}")
public class ProductStockMQListener {

    @Autowired
    private ProductService productService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    private static final int MAX_RETRY = 3;


    /**
     *
     * 重复消费-幂等性
     *
     * 消费失败，重新入队后最大重试次数：
     *  如果消费失败，不重新入队，可以记录日志，然后插到数据库人工排查
     *
     *  消费者这块还有啥问题，大家可以先想下，然后给出解决方案
     *
     * @param productMessage
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    public void releaseProductStock(ProductMessage productMessage, Message message, Channel channel) throws IOException {

        log.info("监听到消息：releaseCouponRecord消息内容：{}", productMessage);
        long msgTag = message.getMessageProperties().getDeliveryTag();

        boolean flag = productService.releaseProductStock(productMessage);

        String retryKey = "retry:product_stock_release:" + productMessage.getTaskId();
        redisTemplate.opsForValue().setIfAbsent(retryKey, "1");

        //防止同个解锁任务并发进入；如果是串行消费不用加锁；加锁有利也有弊，看项目业务逻辑而定
        Lock lock = redissonClient.getLock("lock:product_stock_release:" + productMessage.getTaskId());
        lock.lock();
        try {
            if (flag) {
                //确认消息消费成功
                channel.basicAck(msgTag, false);
            } else {
                int retryTime = Integer.parseInt((String) redisTemplate.opsForValue().get(retryKey));
                if (retryTime >= MAX_RETRY) {
                    channel.basicAck(msgTag, false);
                    //TODO 添加记录到数据库
                    log.error("人工核查");
                } else {
                    log.error("释放商品库存失败 flag=false,{}", productMessage);
                    channel.basicReject(msgTag, true);
                    redisTemplate.opsForValue().set(retryKey, String.valueOf(retryTime + 1));
                }
            }

        } catch (IOException e) {
            int retryTime = Integer.parseInt((String) redisTemplate.opsForValue().get(retryKey));
            if (retryTime >= MAX_RETRY) {
                channel.basicAck(msgTag, false);
                //TODO 添加记录到数据库
                log.error("人工核查");
            } else {
                log.error("释放商品库存异常:{},msg:{}", e, productMessage);
                channel.basicReject(msgTag, true);
                redisTemplate.opsForValue().set(retryKey, String.valueOf(retryTime + 1));
            }
        } finally {
            lock.unlock();
        }
    }

    @RabbitHandler
    public void releaseProductStock(String msg, Message message, Channel channel) throws IOException {
        System.out.println(msg);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }


    }
